package com.wangzeqi.neihanduanzi.discovery;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.wangzeqi.neihanduanzi.base.BaseActivity;
import com.wangzeqi.neihanduanzi.R;
import com.wangzeqi.neihanduanzi.cache.AllLruCacheLoad;
import com.wangzeqi.neihanduanzi.enter.EnterPersonActivity;
import com.wangzeqi.neihanduanzi.entity.AllEntity;
import com.wangzeqi.neihanduanzi.entity.BannersEntity;
import com.wangzeqi.neihanduanzi.home.HomeActivity;
import com.wangzeqi.neihanduanzi.msg.MsgActivity;
import com.wangzeqi.neihanduanzi.news.activity.NewsActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * Created by dllo on 16/1/7.
 */
public class DiscoveryActivity extends BaseActivity implements View.OnClickListener {


    private ImageButton imageButton;
    private DiscoveryAdapter adapter;
    private ListView listView;
    private RequestQueue queue;
    private ViewPagerAdapter vpAdapter;
    private AllEntity allEntity;
    private ViewPager mViewPager;
    private View headView;
    private TextView textView;
    private int currentItem; //当前页面

    private List<String> titles;
    private TextView title;

    private ScheduledExecutorService scheduledExecutorService;
    private List<NetworkImageView> images;
    private String url = "http://ic.snssdk.com/2/essay/discovery/v3/?iid=3442479241&device_id=9638436650&ac=wifi&channel=meizu&aid=7&app_name=joke_essay&version_code=461&version_name=4.6.1&device_platform=android&ssmix=a&device_type=m1+metal&os_api=22&os_version=5.1&uuid=868024023781926&openudid=ca429b874ca7d3b9&manifest_version_code=461";
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //设定时间自动翻页的回调方法
            mViewPager.setCurrentItem(currentItem);
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discovery_activity);
        findViewById(R.id.rl_home_btn).setOnClickListener(this);
        findViewById(R.id.rl_discovery_btn).setOnClickListener(this);
        findViewById(R.id.rl_review_btn).setOnClickListener(this);
        findViewById(R.id.rl_msg_btn).setOnClickListener(this);
        listView = (ListView) findViewById(R.id.discovery_list_view);
        imageButton = (ImageButton) findViewById(R.id.discovery_top_left_ib);
        imageButton.setOnClickListener(this);
        adapter = new DiscoveryAdapter(this);
        listView.setAdapter(adapter);
        addDiscoveryData();
    }

    private void addDiscoveryData() {
        queue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                allEntity = gson.fromJson(response, AllEntity.class);
                adapter.addData(allEntity);
                initHeadView(allEntity);
                listView.addHeaderView(headView);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DiscoveryActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(request);
    }

    private void initHeadView(AllEntity allEntity) {
        this.allEntity = allEntity;
        queue = Volley.newRequestQueue(this);
        AllLruCacheLoad cache = new AllLruCacheLoad();
        final ImageLoader imageloader = new ImageLoader(queue, cache);
        headView = LayoutInflater.from(this).inflate(R.layout.discovery_top,null);
        title = (TextView) headView.findViewById(R.id.discovery_title);
        mViewPager = (ViewPager) headView.findViewById(R.id.discovery_top_vp);
        textView = (TextView) headView.findViewById(R.id.discovery_top_num);
        titles = new ArrayList<>();
        images = new ArrayList<>();


        List<BannersEntity> bannerDetialEties = allEntity.getData().getRotate_banner().getBanners();
        int num = allEntity.getData().getCategories().getCategory_list().size();
        textView.setText(num + "");
        for (BannersEntity bannerDetialEty : bannerDetialEties) {
            titles.add(bannerDetialEty.getBanner_url().getTitle());
            NetworkImageView imageView = new NetworkImageView(this);
            imageView.setDefaultImageResId(R.mipmap.ugc_tip_loading_essay);
            imageView.setErrorImageResId(R.mipmap.ugc_tip_no_connection);
            imageView.setImageUrl(bannerDetialEty.getBanner_url().getUrl_list().get(0).getUrl()
                    , imageloader);
            images.add(imageView);
        }
        title.setText(titles.get(0));
        vpAdapter = new ViewPagerAdapter();
        mViewPager.setAdapter(vpAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                title.setText(titles.get(position));
                currentItem = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        //每隔2秒钟切换一张图片
        scheduledExecutorService.scheduleWithFixedDelay(new Thread(new Runnable() {
            @Override
            public void run() {
                currentItem = (currentItem + 1) % titles.size();
                //更新界面
                handler.obtainMessage().sendToTarget();
            }
        }), 2, 2, TimeUnit.SECONDS);
    }
    private class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return images.size();
        }
        //是否是同一张图片
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            view.removeView(images.get(position));

        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            view.addView(images.get(position));

            return images.get(position);
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rl_home_btn:
                Intent intentHome = new Intent(this, HomeActivity.class);
                startActivity(intentHome);
                finish();
                break;
            case R.id.rl_discovery_btn:
                Intent intentDiscovery = new Intent(this, DiscoveryActivity.class);
                startActivity(intentDiscovery);
                break;
            case R.id.rl_review_btn:
                Intent intentReview = new Intent(this, NewsActivity.class);
                startActivity(intentReview);
                finish();
                break;
            case R.id.rl_msg_btn:
                Intent intentMsg = new Intent(this, MsgActivity.class);
                startActivity(intentMsg);
                finish();
                break;
            case R.id.discovery_top_left_ib:
                Intent intent = new Intent(this, EnterPersonActivity.class);
                startActivity(intent);
                break;
        }
    }
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
